<template>
    <div class="search-bar" @click="e => $emit('click', e)">
        <van-icon name="arrow-left" class="search-header-left" @click.stop="e => $emit('click-left', e)" v-if="leftArrow"/>
        <van-search v-model="localValue" class="search-input"
                    autofocus :readonly="readonly"
                    shape="round" :placeholder="placeholder"
                    :show-action="showAction" :action-text="actionText"
                    @search="handleSearch">
            <template #action>
                <div @click="handleAction">{{actionText}}</div>
            </template>
        </van-search>
    </div>
</template>

<script>
  import { Icon, Search } from "vant"

  export default {
    name: "SearchBar",
    components: {
      [Icon.name]: Icon,
      [Search.name]: Search,
    },
    model: {
      prop: "value",
      event: "change",
    },
    props: {
      value: String,
      showAction: Boolean,
      placeholder: {
        type: String,
        default: "请输入商品名称",
      },
      readonly: Boolean,
      leftArrow: Boolean,
      cancelAction: Boolean,
      actionText: {
        type: String,
        default: "搜索",
      },
    },
    computed: {
      localValue: {
        get() {
          return this.value
        },
        set(value) {
          this.$emit("change", value)
        },
      },
    },
    methods: {
      handleAction() {
        const { localValue, cancelAction } = this
        console.log(localValue)
        if (cancelAction) {
          this.localValue = ""
        }
        this.$emit("action", localValue)

      },
      handleSearch() {
        this.$emit("search", this.localValue)
      },
    },
  }
</script>

<style lang="scss" scoped>
    .search-bar {
        display: flex;
        align-items: center;
        background: #fff;

        .search-header-left {
            padding-left: 12px;
        }

        .search-input {
            flex: 1;
            padding: 8px 12px;
            background: inherit;

            .van-search__action {
                padding: 0 0 0 8px;

                &:active {
                    background: initial;
                }
            }
        }
    }
</style>
